#!/bin/bash

# fail if any commands fails
#set -e
# debug log
#set -x

# Set superuser privileges command if not set
if [[ -z $su ]]; then
  export su="sudo"
fi

# Add arch linux support
$su pacman -S pacman-contrib
  {
    echo "[universe]"
    echo "  Server = https://universe.artixlinux.org/\$arch"
    echo "  Server = https://mirror1.artixlinux.org/universe/\$arch"
    echo "  Server = https://mirror.pascalpuffke.de/artix-universe/\$arch"
    echo "  Server = https://artixlinux.qontinuum.space/artixlinux/universe/os/\$arch"
    echo "  Server = https://mirror1.cl.netactuate.com/artix/universe/\$arch"
    echo "  Server = https://ftp.crifo.org/artix-universe/"
  } | $su tee -a /etc/pacman.conf

$su pacman -Sy artix-archlinux-support
  {
    echo "#[testing]"
    echo "#Include = /etc/pacman.d/mirrorlist-arch"
    echo ""
    echo "[extra]"
    echo "Include = /etc/pacman.d/mirrorlist-arch"
    echo ""
    echo "#[community-testing]"
    echo "#Include = /etc/pacman.d/mirrorlist-arch"
    echo ""
    echo "[community]"
    echo "Include = /etc/pacman.d/mirrorlist-arch"
    echo ""
    echo "#[multilib-testing]"
    echo "#Include = /etc/pacman.d/mirrorlist-arch"
    echo ""
    echo "[multilib]"
    echo "Include = /etc/pacman.d/mirrorlist-arch"
  } | $su tee -a /etc/pacman.conf
$su pacman-key --populate archlinux

arch_file=/etc/pacman.d/mirrorlist-arch.backup
artix_file=/etc/pacman.d/mirrorlist.backup
if [ -f "$artix_file" ]; then
    echo "Mirrorlist $artix_file backup file exists."
else
    echo "Mirrorlist $artix_file backup file does not exists. Creating backup"
    $su cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.backup
fi
if [ -f "$arch_file" ]; then
    echo "Mirrorlist $arch_file backup file exists."
else
    echo "Mirrorlist $arch_file backup file does not exists. Creating backup"
    $su cp /etc/pacman.d/mirrorlist-arch /etc/pacman.d/mirrorlist-arch.backup
fi

echo -e "\033[33;5m THIS WILL TAKE SEVERAL MINUTES... \033[0m"
curl -s "https://gitea.artixlinux.org/packages/artix-mirrorlist/raw/branch/master/mirrorlist" | sed -e 's/^#Server/Server/' -e '/^#/d' | rankmirrors -v -n 5 - > ~/mirrorlist.new
$su mv ~/mirrorlist.new /etc/pacman.d/mirrorlist

echo -e "\033[33;5m THIS WILL TAKE SEVERAL MINUTES... \033[0m"
curl -s "https://archlinux.org/mirrorlist/?protocol=https&use_mirror_status=on" | sed -e 's/^#Server/Server/' -e '/^#/d' | rankmirrors -v -n 5 - > ~/mirrorlist-arch.new
$su mv ~/mirrorlist-arch.new /etc/pacman.d/mirrorlist-arch
